<script lang="ts" setup>
import type { FieldRule, FormInstance } from '@arco-design/web-vue'
import type { CertDomainListItem } from '@/apis/model/cert'
import { Message } from '@arco-design/web-vue'
import { pick } from 'lodash-es'
import { addCertDomainApi, updateCertDomainApi } from '@/apis/modules/cert'
import { getDnsDomainListApi } from '@/apis/modules/dns'

const props = defineProps<IProps>()
const emit = defineEmits(['reload'])
interface IProps {
  record: CertDomainListItem
  list: CertDomainListItem[]
}
const visible = defineModel<boolean>('visible', { required: true })
const getTitle = computed(() => {
  return props.record?.id ? '编辑域名' : '添加域名'
})
const appList = computed<OptionItem[]>(() => {
  const appIds = Array.from(new Set(props.list?.map(v => v.app_id)))
  if (appIds.length === 0)
    return useAppStore().appList || []
  return (
    useAppStore().appList.map((v) => {
      return { ...v, disabled: appIds.includes(v.value) }
    }) || []
  )
})
const formRef = ref<FormInstance>()
const formState = reactive({
  app_id: undefined,
  name: undefined,
  remark: '',
})
const rules: Record<string, FieldRule> = {
  app_id: { required: true, message: '请选择所属应用' },
  name: { required: true, message: '请选择域名' },
}
function handleJump() {
  window.open('/sys/system-domains/domain-list?type=open', '_target')
}
const loading = ref(false)
const domainList = ref<OptionItem[]>([])
async function getDomainList() {
  try {
    loading.value = true
    const res = await getDnsDomainListApi({
      offset: 0,
      limit: 0,
      app_id: formState.app_id,
    })
    loading.value = false
    domainList.value = res.list.map(v => ({ label: v.name, value: v.name }))
  } catch (e) {
    console.error(e)
    loading.value = false
  }
}
async function handleRefresh() {
  await getDomainList()
  formState.name = undefined
  Message.success('更新成功')
}
async function handleSubmit() {
  const error = await formRef.value?.validate()
  if (error)
    return false
  const api_path = props.record?.id ? updateCertDomainApi : addCertDomainApi
  return api_path(formState).then(() => {
    Message.success('操作成功')
    emit('reload')
  })
}
async function handleOpen() {
  await nextTick()
  if (!props.record) {
    formState.name = undefined
    return
  }
  Object.assign(formState, {
    ...pick(props.record, ['app_id', 'remark', 'id']),
  })
  formState.name = props.record?.name
  getDomainList()
}
function handleClose() {
  formRef.value?.resetFields()
}
</script>

<template>
  <resource-dialog
    v-model:visible="visible"
    :title="getTitle"
    :width="480"
    :mask-closable="false"
    :before-ok="handleSubmit"
    :before-close="handleClose"
    :before-open="handleOpen"
  >
    <a-form
      ref="formRef"
      layout="vertical"
      :model="formState"
      :rules="rules"
    >
      <a-form-item
        label="所属应用"
        field="app_id"
        asterisk-position="end"
      >
        <a-select
          v-model="formState.app_id"
          :options="appList"
          :disabled="!!record?.id"
          placeholder="请选择所属应用"
          not-found-content="未获取到所属应用"
          @change="getDomainList"
        />
      </a-form-item>
      <a-form-item
        label="域名"
        field="name"
        asterisk-position="end"
      >
        <a-select
          v-model="formState.name"
          :options="domainList"
          :disabled="!formState.app_id"
          :loading="loading"
          show-footer-on-empty
          placeholder="请选择域名"
          popup-container="#resource"
        >
          <template #footer>
            <div
              class="h-8 flex cursor-pointer items-center gap-x-1 px-3 text-[#00A65B] leading-8"
              @click="handleJump"
            >
              <span class="text-xs leading-[19px]">新建域名</span>
              <i-icons-jump size="14px" />
            </div>
          </template>
        </a-select>
        <a-button
          class="ml-2 shrink-0 text-color-1"
          type="outline"
          :disabled="!formState.app_id"
          @click="handleRefresh"
        >
          <template #icon>
            <i-icons-refresh />
          </template>
        </a-button>
      </a-form-item>
      <a-form-item
        label="备注"
        field="remark"
        asterisk-position="end"
      >
        <a-textarea
          v-model="formState.remark"
          :max-length="200"
          show-word-limit
          :auto-size="{ maxRows: 5, minRows: 5 }"
          placeholder="请输入备注"
        />
      </a-form-item>
    </a-form>
  </resource-dialog>
</template>

<style lang="less" scoped>
:deep(.arco-trigger-popup) {
  .arco-select-dropdown-list-wrapper {
    max-height: 342px !important;
    .arco-select-dropdown-list {
      .arco-select-option:not-last-child {
        margin-top: 4px;
      }
    }
  }
}

:deep(.arco-btn-disabled) {
  background-color: rgb(247, 248, 250) !important;
}
</style>
